<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity {

    public $id;

    CONST ERROR_ACCOUNT_LOCKED = 3;

    public $loginType = 'Front';

    public function authenticate() {

        if ($this->loginType == 'Front') {
            $users = array(
                'demo' => 'demo',
            );
            if (!isset($users[$this->username])) {
                $this->errorCode = self::ERROR_USERNAME_INVALID;
            } elseif ($users[$this->username] !== $this->password) {
                $this->errorCode = self::ERROR_PASSWORD_INVALID;
            } else {
                $this->errorCode = self::ERROR_NONE;
            }
        }
        if ($this->loginType == 'Back') {
            $user = User::model()->find('email=:email', array(':email' => $this->username));
            if (!$user)
                $this->errorCode = self::ERROR_USERNAME_INVALID;
            elseif ($user->password !== md5($this->password)){
                $this->errorCode = self::ERROR_PASSWORD_INVALID;
            } elseif ($user->status == User::ACCOUNT_LOCKED) {
                $this->errorCode = self::ERROR_ACCOUNT_LOCKED;
            } else {
                $this->id = $user->id;
                $auth = Yii::app()->authManager;
                if (!$auth->isAssigned($user->role, $this->id)) {

                    if ($auth->assign($user->role, $this->id)) {
                        Yii::app()->authManager->save();
                    }
                } else {
                    echo $user->role;
                }
//                $roleAssigned = Yii::app()->authManager->getRoles(Yii::app()->user->id);
//                var_dump($roleAssigned);
//                exit();
                $user->last_active = date('Y-m-d H:i:s');
                $this->errorCode = self::ERROR_NONE;
                $user->update();
                Yii::app()->user->setState('fullname', $user->fullname);
                Yii::app()->user->setState('avatar', $user->avatar);
            }
        }
        return !$this->errorCode;
    }

    public function getId() {
        return $this->id;
    }

}